package game.pong.views.components
{
	import flash.events.Event;
	import flash.events.TimerEvent;
	
	import game.pong.business.Gamespeed;
	
	public class ComputerPaddle3D extends AbstractPaddle3D
	{
		/** Timer to handle the refresh method */
		private var ticker : Gamespeed = new Gamespeed();
		
		public var topBound : Number;
		public var bottomBound : Number;
		
		/** The ball we try to hit */
		public var ball : Ball3D;
		
		/** Maximum distance the paddle can move per update */
		private var maxSpeed : Number = 9;
		
		/** Constructor	 */	
		public function ComputerPaddle3D(init : Object = null)
		{
			super(init);
			ticker.addEventListener(TimerEvent.TIMER, refresh);
		}
		
		/**
		 * Update by trying to hit the ball. We try to hit the ball at a random spot
		 * on the paddle.
		 */
		public function refresh(event : Event) : void
		{
			// Compute a random spot we'd like to hit the ball at
			var hitSpot : Number = Math.random() % (maxY * 2);
			
			// Compute the middle of the ball
			var ballMiddle : Number = (ball.y + gameArea.maxY) + ball.maxY;
	
			// Get the distance we'd like to move to hit the ball
			var ballDelta : Number = (y + gameArea.maxY) + hitSpot - ballMiddle;
	
			// Compute the amount to move to hit the ball, or the maximum we can move
			// toward hitting it
			var moveAmount : Number = Math.min(Math.abs(ballDelta), this.maxSpeed);
			
			// The ball is below us, try to go up to hit it
			if (ballDelta < 0)
			{
				this.y = Math.max(gameArea.minY, Math.min(gameArea.maxY - maxY, this.y + moveAmount));
			}
			// The ball is above us, try to go down to hit it
			else
			{
				this.y = Math.max(gameArea.minY, Math.min(gameArea.maxY - maxY, this.y - moveAmount));
			}
		}
		
		public function start() : void
		{
			ticker.start();
		}
		
		
		public function stop() : void
		{
			ticker.stop();
		} 
		
	}
}